package download;

import java.io.*;

/**
 * Created by zy on 2019/4/29.
 */
public class Merge {
    //下载分段视频合并为一
    public static void main(String a[]) throws FileNotFoundException, IOException {
        File file = new File("D:/movie/done");
        //RandomAccessFile randomAccessFile = null;
        //randomAccessFile = new RandomAccessFile(new File(file, "merge.ts").getPath(), "rw");
        //for (File file1 : file.listFiles()) {
        //    InputStream inputStream = new FileInputStream(file1);
        //    byte[] buf = new byte[inputStream.available()];
        //    int length = 0;
        //    try {
        //        while (length < inputStream.available()) {
        //            length = inputStream.read(buf, length, inputStream.available() - length);
        //            randomAccessFile.write(buf);
        //        }
        //    } catch (IOException e) {
        //        e.printStackTrace();
        //    }
        //    inputStream.close();
        //}
        //randomAccessFile.close();
        joinFileDemo(file.listFiles());
    }

    private static void joinFileDemo(File[] src) {
        for (int i = 0; i < src.length; i++) {
            File file = (src[i]);
            //String fileName = file.getName().substring(0, file.getName().indexOf("_"));
            //String endName = file.getName().substring(file.getName().lastIndexOf("."));

            //StringBuffer sb = new StringBuffer();
            //sb.append(file.getParent()).append("\\").append(fileName)
            //        .append(endName);
            //System.out.println(sb.toString());
            try {
                //读取小文件的输入流
                InputStream in = new FileInputStream(file);
                //写入大文件的输出流
                File file2 = new File("D:/movie/done/me.ts");
                OutputStream out = new FileOutputStream(file2, true);
                int len = -1;
                byte[] bytes = new byte[10 * 1024 * 1024];
                while ((len = in.read(bytes)) != -1) {
                    out.write(bytes, 0, len);
                }
                out.close();
                in.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println("文件合并完成！");
    }
}
